package com.my.swas.sso.common.shiro;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.my.swas.common.base.ResponseResult;
import com.my.swas.common.jwt.JWTToken;
import com.my.swas.common.utils.CookieUtils;
import com.my.swas.common.constans.CommConst;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Response;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @Description: 定制了JWT加密方式 所以要扩展 BasicHttpAuthenticationFilter
 *                代码的执行流程preHandle->isAccessAllowed->isLoginAttempt->executeLogin
 * @author: :MaYong
 */
public class JWTFilter extends BasicHttpAuthenticationFilter {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 判断用户是否可以登入(是否有令牌)。
     * 检测header里面是否包含Authorization字段即可
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        if(logger.isDebugEnabled()) {
            logger.info("url:{}", request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getServletContext().getContextPath());
        }
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        String authorization = httpServletRequest.getHeader(JWTToken.AUTH_TOKEN);
        String url = getPathWithinApplication(request);
        if (StringUtils.isEmpty(authorization)) {//如何是sso系统访问，验证Cookie
            if(url.contains(CommConst.ADMIN)){
                authorization = CookieUtils.getCookieValue(httpServletRequest, JWTToken.AUTH_TOKEN);
                if(StringUtils.isEmpty(authorization)){
                    return false;
                }
            }else{
                return false;
            }
        }
        if (StringUtils.isEmpty(authorization) && url.contains(CommConst.API)) {//如果是第三方系统访问，验证Header
            responseError(request, response);
        }
        return true;
    }

    /**
     * 登录扩展判断
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        String authorization = httpServletRequest.getHeader(JWTToken.AUTH_TOKEN);
        if(StringUtils.isEmpty(authorization)){
            authorization =  CookieUtils.getCookieValue(httpServletRequest,JWTToken.AUTH_TOKEN);
        }
        JWTToken token = new JWTToken(authorization);
        Subject subject = SecurityUtils.getSubject();
        //提交给realm进行登入，如果错误他会抛出异常并被捕获
        if(!subject.isAuthenticated()) {
            subject.login(token);
        }
        return true;
    }

    /**
     * 表示是否允许访问 ，如果允许访问返回true，否则false；
     * 这里我们详细说明下为什么最终返回的都是true，即允许访问
     * 例如我们提供一个地址 GET /article
     * 登入用户和游客看到的内容是不同的
     * 如果在这里返回了false，请求会被直接拦截，用户看不到任何东西
     * 所以我们在这里返回true，Controller中可以通过 subject.isAuthenticated() 来判断用户是否登入
     * 如果有些资源只有登入用户才能访问，我们只需要在方法上面加上 @RequiresAuthentication 注解即可
     * 但是这样做有一个缺点，就是不能够对GET,POST等请求进行分别过滤鉴权(因为我们重写了官方的方法)，但实际上对应用影响不大
     * 表示写在拦截器中括号里面的字符串 mappedValue 就是 [urls] 配置中拦截器参数部分
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        return false;
    }

    /**
     * onAccessDenied：表示当访问拒绝时是否已经处理了；如果返回 true 表示需要继续处理；如果返回 false 表示该拦截器实例已经处理了，将直接返回即可。
     * isAccessAllowed 返回false之后调用
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        if (isLoginAttempt(request, response)) {
            try {
                this.executeLogin(request, response);
                return true;
            } catch (Exception e) {
                return  false;
            }
        }else{
            if(isAjax(request)){
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json");
                Map<String,Object> stringMap = Maps.newHashMap();
                stringMap.put("status",1001);
                stringMap.put("message","登录状态失效，请重新登录");
                response.getWriter().write(JSONObject.toJSONString(stringMap));
            }else{
                WebUtils.issueRedirect(request, response,this.getLoginUrl());
            }
        }

        return false;
    }




    /**
     * 对跨域提供支持
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;

        }
        return super.preHandle(request, response);
    }

    /**
     * 非法url返回身份错误信息
     */
    private void responseError(ServletRequest request, ServletResponse response) {
        PrintWriter out = null;
        try {
            response.setCharacterEncoding("utf-8");
            out = response.getWriter();
            response.setContentType("application/json; charset=utf-8");
            out.print(JSONObject.toJSONString(ResponseResult.error("Heard中缺少"+JWTToken.AUTH_TOKEN+"属性")));
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (out != null) {
                out.close();
            }
        }
    }

    public static boolean isAjax(ServletRequest request) {
        String header = ((HttpServletRequest) request).getHeader("X-Requested-With");
        if ("XMLHttpRequest".equalsIgnoreCase(header)) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

}